<template>
  <div>
    <div class="p-5">
      <div class="handle-box">
        <!-- <el-input placeholder="请输入部门名称" v-model="departmentQuery.departmentName" class="handle-input mr10" @input="searchDepartment">
        <template #append>
          <el-button @click="searchDepartment"> 搜索 </el-button>
        </template>
      </el-input> -->
        <el-select
          v-model="departmentQuery.departmentState"
          placeholder="请选择部门状态"
          class="handle-select mr10"
          @change="searchDepartment"
          clearable
        >
          <el-option
            v-for="item in departmentStateOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        <el-input
          placeholder="请输入部门名称"
          v-model="departmentQuery.departmentName"
          suffix-icon="el-icon-search"
          style="width: 250px"
          @input="searchDepartment"
        >
        </el-input>
      </div>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card class="h-600">
            <el-tree
              v-loading="treeLoading"
              element-loading-text="加载中"
              :data="data"
              :props="defaultProps"
              :filter-node-method="filterNode"
              @node-click="handleNodeClick"
              ref="tree"
              node-key="id"
              :expand-on-click-node="false"
              :default-expand-all="true"
            >
              <template #default="{ node, data }">
                <span class="custom-tree-node">
                  <span class="align-middle"
                    ><svg-icon
                      :icon-class="'禁用'"
                      v-if="data.state === 2"
                    ></svg-icon>
                    <span class="label ml-1">{{ node.label }}</span>
                  </span>

                  <span>
                    <!-- <a @click.stop="openAddDepartmentDialog(data, 0)"> 分组 </a> -->
                    <!-- <a @click.stop="openAddDepartmentDialog(data, 1)" v-if="data.id !== '01'"> 同级 </a> -->
                    <el-tooltip
                      effect="dark"
                      content="添加同级部门"
                      placement="top"
                      v-if="data.id !== '01'"
                    >
                      <svg-icon
                        :icon-class="'添加同级目录'"
                        class="text-xl hover: cursor-default inline"
                        @click.stop="openAddDepartmentDialog(data, 1)"
                      ></svg-icon>
                    </el-tooltip>
                    <el-tooltip
                      effect="dark"
                      content="添加子部门"
                      placement="top"
                      class="ml-1"
                    >
                      <svg-icon
                        :icon-class="'添加子目录'"
                        class="text-xl hover: cursor-default inline"
                        @click.stop="openAddDepartmentDialog(data, 2)"
                      ></svg-icon>
                    </el-tooltip>
                    <!-- <a @click.stop="openAddDepartmentDialog(data, 2)"> 下属 </a> -->
                  </span>
                </span>
              </template>
            </el-tree>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card class="h-600" v-if="currentNode.departmentName">
            <div class="description" :column="1" align="left">
              <div class="title">
                部门详情—— {{ currentNode.departmentName }}
              </div>
              <div>部门名: {{ currentNode.departmentName }}</div>
              <!-- <div label="部门编号">{{ currentNode.departmentNumber }}</div> -->
              <div>
                部门状态:
                <el-switch
                  style="display: block"
                  v-model="currentNode.departmentState"
                  disabled
                >
                </el-switch>
              </div>
              <div>备注: {{ currentNode.departmentDesc }}</div>
            </div>
            <el-row justify="end">
              <el-col :span="6" :offset="18">
                <el-button plain @click="editDepartmentDialogVisible = true"
                  >编辑</el-button
                >
                <el-button plain @click="deleteDept">删除</el-button>
              </el-col>
            </el-row>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <el-dialog
      :title="addDepartmentDialogTitle"
      :visible.sync="addDepartmentDialogVisible"
      width="30%"
      @closed="closedAddDepartmentDialog"
      :close-on-click-modal="false"
    >
      <el-form
        ref="addDepartmentFormRef"
        :model="addDepartmentForm"
        label-width="80px"
        :rules="departmentFormRules"
      >
        <el-form-item label="部门名称" prop="departmentName">
          <el-input v-model.trim="addDepartmentForm.departmentName"></el-input>
        </el-form-item>
        <!-- <el-form-item label="部门编号">
        <el-input v-model="addDepartmentForm.departmentNumber"></el-input>
      </el-form-item> -->
        <el-form-item label="部门状态" prop="departmentState">
          <el-switch v-model="addDepartmentForm.departmentState"></el-switch>
        </el-form-item>
        <el-form-item label="备注" prop="departmentDesc">
          <el-input v-model.trim="addDepartmentForm.departmentDesc"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDepartmentDialogVisible = false"
            >取 消</el-button
          >
          <el-button type="primary" @click="addDept">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog
      title="编辑部门"
      :visible.sync="editDepartmentDialogVisible"
      width="30%"
      @closed="closedEditDepartmentDialog"
      :close-on-click-modal="false"
    >
      <el-form
        ref="editDepartmentFormRef"
        :model="editDepartmentForm"
        label-width="80px"
        :rules="departmentFormRules"
      >
        <el-form-item label="部门名称" prop="departmentName">
          <el-input v-model.trim="editDepartmentForm.departmentName"></el-input>
        </el-form-item>
        <!-- <el-form-item label="部门编号">
        <el-input v-model="editDepartmentForm.departmentNumber"></el-input>
      </el-form-item> -->
        <el-form-item label="部门状态" prop="departmentState">
          <el-switch v-model="editDepartmentForm.departmentState"></el-switch>
        </el-form-item>
        <el-form-item label="备注" prop="departmentDesc">
          <el-input v-model.trim="editDepartmentForm.departmentDesc"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDepartmentDialogVisible = false"
            >取 消</el-button
          >
          <el-button type="primary" @click="updateDept">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  getDepartmentTree,
  addDepartment,
  updateDepartment,
  deleteDepartment,
} from '@/api/department'
function transformTree(tree) {
  let arr = []
  tree.forEach((item) => {
    console.log(item)
    if (item.childTree.length !== 0) {
      item.childTree = transformTree(item.childTree)
    }
    arr.push({
      id: item.pkid,
      label: item.deptName,
      children: item.childTree,
      number: item.deptNumber,
      state: item.deptStatus,
      desc: item.remark,
    })
  })
  return arr
}
export default {
  name: 'department',
  data() {
    return {
      departmentQuery: {
        departmentName: '',
        departmentState: null,
      },
      editDepartmentForm: {
        departmentName: '',
        // departmentNumber: "",
        departmentState: true,
        departmentDesc: '',
      },
      departmentStateOptions: [
        {
          value: 1,
          label: '启用',
        },
        {
          value: 2,
          label: '禁用',
        },
      ],
      treeLoading: false,
      data: [],
      defaultProps: {
        children: 'children',
        label: 'label',
      },
      addDepartmentDialogVisible: false,
      addDepartmentDialogType: 0,
      currentNode: {
        departmentName: '',
        // departmentNumber: "",
        departmentState: true,
        departmentDesc: '',
      },
      editDepartmentDialogVisible: false,
      addDepartmentForm: {
        departmentName: '',
        // departmentNumber: "",
        departmentState: true,
        departmentDesc: '',
        parendNodeId: 0,
      },
      departmentFormRules: {
        departmentName: [
          {
            required: true,
            message: '请输入部门名称',
            trigger: ['blur', 'change'],
          },
        ],
        departmentState: [
          {
            required: true,
            message: '请选择部门状态',
            trigger: ['blur', 'change'],
          },
        ],
      },
    }
  },
  methods: {
    searchDepartment() {
      this.$refs.tree.filter(this.departmentQuery)
    },
    filterNode(query, data) {
      console.log(query, data)
      if (!query.departmentName && !query.departmentState) return true
      if (!query.departmentName) return data.state === query.departmentState
      if (!query.departmentState)
        return data.label.indexOf(query.departmentName) !== -1
      return (
        data.label.indexOf(query.departmentName) !== -1 &&
        data.state === query.departmentState
      )
    },
    handleNodeClick(data) {
      console.log(
        '🚀 ~ file: department.vue ~ line 134 ~ handleNodeClick ~ data',
        data
      )
      this.currentNode.departmentName = data.label
      // this.currentNode.departmentNumber = data.number;
      this.currentNode.departmentState = data.state === 1 ? true : false
      this.currentNode.departmentDesc = data.desc
      this.currentNode.id = data.id

      this.editDepartmentForm.departmentName = data.label
      // this.editDepartmentForm.departmentNumber = data.number;
      this.editDepartmentForm.departmentState = data.state === 1 ? true : false
      this.editDepartmentForm.departmentDesc = data.desc
    },
    openAddDepartmentDialog(node, type) {
      this.addDepartmentDialogVisible = true
      this.addDepartmentDialogType = type
      const parentNodeId = this.$refs.tree.getNode(node.id).parent.data.id
      if (this.addDepartmentDialogType === 0)
        this.addDepartmentForm.parendNodeId = '-1'
      if (this.addDepartmentDialogType === 1)
        this.addDepartmentForm.parendNodeId = parentNodeId ?? '-1'
      if (this.addDepartmentDialogType === 2)
        this.addDepartmentForm.parendNodeId = node.id
    },
    deleteDept() {
      this.$confirm(
        `此操作将删除该部门(${this.currentNode.departmentName}), 是否继续?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
        .then(() => {
          deleteDepartment(this.currentNode.id).then((res) => {
            if (res.success) {
              this.editDepartmentDialogVisible = false
              this.$message({
                type: 'success',
                message: '删除成功!',
              })
              this.fetchData()
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    updateDept() {
      this.$refs.editDepartmentFormRef.validate((valid) => {
        if (valid) {
          const data = {
            deptName: this.editDepartmentForm.departmentName,
            deptStatus: this.editDepartmentForm.departmentState ? 1 : 2,
            remark: this.editDepartmentForm.departmentDesc,
          }
          updateDepartment(this.currentNode.id, data).then((res) => {
            if (res.success) {
              this.$message.success('编辑成功')
              this.editDepartmentDialogVisible = false
              this.fetchData()
            }
          })
        }
      })
    },
    addDept() {
      this.$refs.addDepartmentFormRef.validate((valid) => {
        if (valid) {
          const data = {
            deptName: this.addDepartmentForm.departmentName,
            // deptNumber: this.addDepartmentForm.departmentNumber,
            deptStatus: this.addDepartmentForm.departmentState ? 1 : 2,
            remark: this.addDepartmentForm.departmentDesc,
            parentId: this.addDepartmentForm.parendNodeId,
          }
          addDepartment(data).then((res) => {
            this.addDepartmentDialogVisible = false
            if (res.success) {
              this.$message.success('添加成功')
              this.fetchData()
            }
          })
        }
      })
    },
    fetchData() {
      this.treeLoading = true
      // 重置搜索参数
      this.departmentQuery.departmentName = ''
      this.departmentQuery.departmentState = null
      getDepartmentTree().then((res) => {
        console.log(
          '🚀 ~ file: department.vue ~ line 61 ~ getDepartmentTree ~ res',
          res
        )
        this.treeLoading = false
        let temp = transformTree(res.data)
        this.handleNodeClick(temp[0])
        this.data = temp
      })
    },
    closedAddDepartmentDialog() {
      this.$refs.addDepartmentFormRef.resetFields()
    },
    closedEditDepartmentDialog() {
      for (const key in this.editDepartmentForm) {
        this.editDepartmentForm[key] = this.currentNode[key]
      }
    },
  },
  mounted() {
    this.fetchData()
  },
  computed: {
    addDepartmentDialogTitle() {
      return ['添加分组', '添加同级部门', '添加子部门'][
        this.addDepartmentDialogType
      ]
    },
  },
}
</script>

<style lang="scss" scoped>
.container {
  margin: 20px;
}
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 200px;
}

.handle-input {
  width: 300px;
}
.table {
  width: 100%;
  font-size: 14px;
}
.mr10 {
  margin-right: 10px;
}
.el-card {
  height: 800px;
}
.el-switch {
  display: inline-block !important;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
.el-card {
  height: 100%;
  overflow-x: hidden;
  overflow-y: auto;
}
.h-full {
  height: 100%;
}
.h-600 {
  height: calc(100vh - 200px);
}
.p-5 {
  padding: 20px;
}
.description {
  font-size: 14px;
  line-height: 2em;
  .title {
    font-size: 16px;
    font-weight: 700;
    color: #303133;
  }
}
</style>
